import {USER_INFO_KEY} from '../constants/common';
import {save} from '../utils/Storage';
import {request} from '../utils/request';
import {flow, makeAutoObservable, observable, action} from 'mobx';
import Loading from '../components/widget/Loading';
/**
 * user store 全局存储
 */
class UserStore {
  userInfo: UserInfo = {} as UserInfo;
  constructor() {
    makeAutoObservable(this, {
      userInfo: observable,
      requestLogin: action,
      setUserInfo: action,
    });
  }
  //   requestLogin = async (
  //     phone: string,
  //     password: string,
  //     callback?: (success: boolean) => void,
  //   ) => {
  //     try {
  //       const params = {
  //         name: phone,
  //         pwd: password,
  //       };
  //       const {data} = await request('login', params);
  //       if (data) {
  //         this.useInfo = data;
  //         callback?.(true);
  //       } else {
  //         callback?.(false);
  //       }
  //     } catch (error) {
  //       console.log(error);
  //       callback?.(false);
  //     }
  //   };

  requestLogin = flow(function* (
    this: UserStore, // 方便使用this指针
    phone: string,
    password: string,
    callback?: (success: boolean) => void,
  ) {
    Loading.show();
    try {
      const params = {
        name: phone,
        pwd: password,
      };

      console.log(JSON.stringify(params));
      const {data} = yield request('login', params);
      if (data) {
        this.userInfo = data;
        save(USER_INFO_KEY, JSON.stringify(this.userInfo));
        callback?.(true);
      } else {
        callback?.(false);
      }
    } catch (error) {
      console.log(error);
      callback?.(false);
    } finally {
      Loading.hide();
    }
  });

  setUserInfo = (userInfo: UserInfo) => {
    this.userInfo = userInfo;
  };
}

/**
 * ESM单例导出
 */
export default new UserStore();
